# -*- coding: utf-8 -*-
from decimal import Decimal
from flask import Blueprint, render_template, request, flash, redirect
from sqlalchemy import or_, and_

from application import db, app
from common.libs import Helper
from common.libs.FoodService.FoodService import FoodService
from common.libs.Helper import ops_render, getDictFilterField
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.models.foods import FoodCate
from common.models.foods.Food import Food
from common.models.foods.FoodSaleChangeLog import FoodSaleChangeLog
from common.models.foods.FoodStockChangeLog import FoodStockChangeLog

route_food = Blueprint('food_page', __name__)


@route_food.route("/index")
def index():
    # list = Helper.getDictFilterField(FoodCate.FoodCat, 'id', 'id', [])
    # 根据getDictFilterField可以查出以指定key为键的所有model数据
    page = request.args.get('p') if 'p' in request.args else 1
    status = int(request.args.get('status')) if 'status' in request.args else 1
    cate_id = int(request.args.get('cate_id')) if 'cate_id' in request.args else 0
    kword = request.args.get('kword') if 'kword' in request.args else ''
    offest = (page - 1)*app.config['PAGE_SIZE']
    limit = page * app.config['PAGE_SIZE']
    cates = FoodCate.FoodCat.query.all()

    # query = db.session.query(FoodCate.FoodCat.name, Food)
    # list = query.join(Food, and_(FoodCate.FoodCat.id == Food.cat_id)).all()

    # query = db.session.query(FoodCate.FoodCat.name, Food.name)
    # list = query.filter(FoodCate.FoodCat.id == Food.cat_id).all()

    query = Food.query
    if status != -1:
        query = query.filter_by(status=status)
    if cate_id != 0 and cate_id:
        query = query.filter_by(cat_id=cate_id)
    if kword:
        query = query.filter(or_(Food.name.like('%'+kword+'%'), Food.tags.like('%'+kword+'%')))
    foods = query.all()[offest:limit]
    pages_params = {
        'total': len(foods),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace('?p={}'.format(page), '')
    }
    pages = Helper.iPagination(pages_params)
    return ops_render("food/index.html", context={'pages': pages, 'foods': foods, 'cates': cates, 'searchParams': {'status': status, 'cate_id': cate_id, 'kword': kword, }})


@route_food.route("/info")
def info():
    fo_id = request.args.get('fo_id', 0)
    food = Food.query.get(fo_id)
    if not food:
        flash(message='没有找到此菜品', category='error')
        return redirect(UrlManager.buildUrl('food/index'))
    stockChangeLog = FoodStockChangeLog.query.filter_by(food_id=food.id).all()
    saleChangeLog = FoodSaleChangeLog.query.filter_by(food_id=food.id).all()
    return ops_render("food/info.html", context={'food': food, 'stockModel': stockChangeLog, 'saleModel': saleChangeLog})


@route_food.route("/set", methods=['GET', 'POST'])
def set():
    if request.method == 'GET':
        fo_id = request.args.get('fo_id', default=0)
        cates = FoodCate.FoodCat.query.all()
        food = Food.query.filter_by(id=fo_id).first()
        # if not food:
        #     flash(message='没有找到此商品', category='error')
        #     return redirect(UrlManager.buildUrl('food/index'))
        return ops_render("food/set.html", context={'cates': cates, 'food': food})
    else:
        name = request.form.get('name')
        cate_id = request.form.get('cate_id')
        price = request.form.get('price')
        pic = request.form.get('pic')
        stock = request.form.get('stock')
        tags = request.form.get('tags')
        desc = request.form.get('desc')
        id = request.form.get('id')

        price = Decimal(price).quantize(Decimal('0.00'))
        if not cate_id:
            return Restful.param_error(msg='参数不合法！')

        if float(price) < 0:
            return Restful.format_error(msg='参数不合法！', code=400)

        sock_before = 0
        food = Food.query.filter_by(id=id).first()
        if not food:
            food = Food()
            food.name = name
            food.cat_id = cate_id
            food.price = price
            food.main_image = pic
            food.stock = stock
            food.tags = tags
            food.summary = desc
            db.session.add(food)
            db.session.commit()
        else:
            food.name = name
            food.cat_id = cate_id
            food.price = price
            food.main_image = pic
            food.stock = stock
            food.tags = tags
            food.summary = desc
            food.updated_time = Helper.geneDatetime()
            db.session.commit()

            sock_before = food.stock

            FoodService.setStockChange(food.id, int(stock)-int(sock_before), "后台修改")

        return Restful.success(msg='更新成功！')


@route_food.route("/cat")
def cat():
    st = int(request.args.get('st', default=1))
    if st == -1:
        st = 1
    if st != 0 and st != 1 and st != -1:
        flash('参数错误')
        return redirect(UrlManager.buildUrl('food/index'))
    query = FoodCate.FoodCat.query
    cates = query.filter_by(status=st).order_by(FoodCate.FoodCat.weight.desc(), FoodCate.FoodCat.id.desc()).all()
    return ops_render("food/cat.html", {'cates': cates})


@route_food.route("/cat-set", methods=['GET', 'POST'])
def catSet():
    if request.method == 'GET':
        id = request.args.get('id')
        if id:
            cate = FoodCate.FoodCat.query.get(id)
            if not cate:
                flash(message='没有找到这个分类', category='error')
                return redirect(UrlManager.buildUrl('food/index'))
            return ops_render("food/cat_set.html", {'cate': cate})
        return ops_render("food/cat_set.html")
    else:
        name = request.form.get('name')
        weight = request.form.get('weight')
        method = request.form.get('method')
        id = request.form.get('id')
        if not name or not weight:
            return Restful.param_error('缺少参数')
        if not weight.isdigit():
            return Restful.param_error(msg='权重必须是数字')
        if method == 'add':
            cate = FoodCate.FoodCat()
            cate.name = name
            cate.weight = weight
            db.session.add(cate)
            db.session.commit()
            return Restful.success('添加成功')
        else:
            if not id:
                return Restful.param_error('缺少参数')
            cate = FoodCate.FoodCat.query.get(id)
            if not cate:
                return Restful.notfound_error('没有找到此分类')
            cate.name = name
            cate.weight = weight
            db.session.commit()
            return Restful.success('更新成功')


@route_food.route('/cat-del', methods=['POST'])
def delete():
    id = request.form.get('id')
    if not id:
        return Restful.param_error('缺少参数')
    cate = FoodCate.FoodCat.query.get(id)
    if not cate:
        return Restful.notfound_error('未找到此用户')
    cate.status = 0
    db.session.commit()
    return Restful.success('删除成功！')
